package org.jtzc.springaiagent.agent.adaptive;

import org.jtzc.springaiagent.agent.BaseAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wu chuang
 * @description
 */
@Service
public class AdaptiveAgent implements BaseAgent {
    private final List<BaseAgent> availableAgents;
    private final PerformanceTracker performanceTracker;
    private BaseAgent currentAgent;

    @Autowired
    public AdaptiveAgent(
            @Qualifier("fastAgent") BaseAgent fastAgent,
            @Qualifier("accurateAgent") BaseAgent accurateAgent,
            @Qualifier("balancedAgent") BaseAgent balancedAgent,
            PerformanceTracker performanceTracker) {

        this.availableAgents = List.of(fastAgent, accurateAgent, balancedAgent);
        this.performanceTracker = performanceTracker;
        this.currentAgent = balancedAgent; // 默认
    }

    @Override
    public AgentResponse execute(AgentRequest request) {
        // 根据当前负载和性能选择最佳代理
        evaluateAndSwitchAgent();

        long startTime = System.currentTimeMillis();
        AgentResponse response = currentAgent.execute(request);
        long duration = System.currentTimeMillis() - startTime;

        // 跟踪性能
        performanceTracker.recordPerformance(
                currentAgent.getClass().getSimpleName(),
                request.prompt(),
                duration,
                response.metadata().get("quality")
        );

        return response;
    }

    private void evaluateAndSwitchAgent() {
        Map<String, Double> agentScores = new HashMap<>();

        // 根据性能指标计算分数
        for (BaseAgent agent : availableAgents) {
            String agentName = agent.getClass().getSimpleName();
            PerformanceMetrics metrics = performanceTracker.getMetrics(agentName);

            double score = calculateScore(
                    metrics.averageResponseTime(),
                    metrics.successRate(),
                    metrics.averageQualityScore()
            );

            agentScores.put(agentName, score);
        }

        // 选择最高分的代理
        String bestAgent = Collections.max(agentScores.entrySet(), Map.Entry.comparingByValue()).getKey();

        this.currentAgent = availableAgents.stream()
                .filter(a -> a.getClass().getSimpleName().equals(bestAgent))
                .findFirst()
                .orElse(currentAgent);
    }

    private double calculateScore(double responseTime, double successRate, double quality) {
        // 简化的评分算法 - 可根据业务需求调整
        return (0.4 * (1 - normalize(responseTime, 0, 5000))) +
                (0.3 * successRate) +
                (0.3 * quality);
    }

    private double normalize(double value, double min, double max) {
        return Math.min(1, Math.max(0, (value - min) / (max - min)));
    }
}

